package com.m1.tzolkin.model.technos;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Collection;
import java.util.HashSet;

import com.m1.tzolkin.model.board.ITZBoard;
import com.m1.tzolkin.model.exceptions.StepMoveException;
import com.m1.tzolkin.model.players.ITZPlayer;
import com.m1.tzolkin.model.technos.ITechnology.TechLevel;
import com.m1.tzolkin.model.util.zone.StepsZonesManager;

public class TechnologiesManager extends StepsZonesManager<ITechnology, ITZPlayer> implements ITechnologiesManager {

	// ATTRIBUTS
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -1103545211154564488L;
	private final ITZBoard board;
	private final PropertyChangeSupport listeners;
	
	// CONSTRUCTEUR
	
	public TechnologiesManager(ITZBoard b) {
		super(Technologies.values());
		board = b;
		listeners = new PropertyChangeSupport(this);
	}
	
	// REQUETES
	
	@Override
	public PropertyChangeListener[] getPropertyChangeListeners() {
		return listeners.getPropertyChangeListeners();
	}

	@Override
	public Collection<TechLevel> getTechs(ITZPlayer p) {
		Collection<TechLevel> res = new HashSet<TechLevel>();
		TechLevel[] lvl;
		for (ITechnology t : getZones()) {
			lvl = t.getLevels();
			for (int i = 1; i <= getPosition(t, p); ++i) {
				res.add(lvl[i - 1]);
			}
		}
		return res;
	}
	
	// COMMANDES
	
	@Override
	public void addPropertyChangeListener(PropertyChangeListener l) {
		listeners.addPropertyChangeListener(l);
	}
	
	@Override
	public void removePropertyChangeListener(PropertyChangeListener l) {
		listeners.removePropertyChangeListener(l);
	}
	
	@Override
	public void up(ITechnology t, ITZPlayer p) {
		try {
			if (getPosition(t, p) + 1 == t.getHeight()) {
				t.getLastAction().doAction(board, p);
			} else {
				super.up(t, p);
				listeners.firePropertyChange("tech", null, null);
			}
		} catch (Exception e) { /* Rien */ }
	}
	
	@Override
	public void down(ITechnology t, ITZPlayer p) throws StepMoveException {
		throw new StepMoveException();
	}

}
